﻿using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Xml.Linq;

namespace NetSurveillance.WebApp.Utilities
{
    public static class Connector
    {
        public static bool IsListening { get; set; }

        public static bool SendAction(XElement actionXml, string ip, int port, bool isAutoSendOver = true)
        {
            if (actionXml == null || string.IsNullOrEmpty(ip) || port <= 0)
                return false;
            var udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            try
            {
                var sendEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
                //client.Connect(IPAddress.Parse(ip), port);
                byte[] actionBytes =
                    Encoding.UTF8.GetBytes(actionXml.ToString());
                //client.Send(actionBytes, actionBytes.Length);
                udpSocket.SendTo(actionBytes, actionBytes.Length, SocketFlags.None, sendEndPoint);

                if (isAutoSendOver)
                {
                    byte[] overActionBytes = Encoding.UTF8.GetBytes("xmlisover");
                    udpSocket.SendTo(overActionBytes, overActionBytes.Length, SocketFlags.None, sendEndPoint);
                }
            }
            catch (SocketException socketEx)
            {
                //todo:log socketEx
                return false;
            }
            finally
            {
                //client.Close();
                udpSocket.Close();
            }
            return true;
        }

        public static bool SendOver(string ip, int port)
        {
            var sendEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
            var udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            try
            {
                byte[] actionBytes = Encoding.UTF8.GetBytes("xmlisover");
                udpSocket.SendTo(actionBytes, actionBytes.Length, SocketFlags.None, sendEndPoint);
            }
            finally
            {
                udpSocket.Close();
            }
            return true;
        }

        public static void Listen(int listenPort)
        {
            var udpClient = new UdpClient(listenPort);
            IPEndPoint remoteIpEndPoint = null;
            try
            {
                IsListening = true;
                while (IsListening)
                {
                    byte[] receiveBytes = udpClient.Receive(ref remoteIpEndPoint);
                    string receiveStr = Encoding.UTF8.GetString(receiveBytes);
                }
            }
            finally
            {
                IsListening = false;
                udpClient.Close();
            }
        }
    }
}